<template>
	<view class="wordsDetailBox">
		<view class="wordBox">
			<view class="image" v-if="wordsDetail.wordPic">
				<img :src="wordsDetail.wordPic" />
			</view>
			<view class="words">{{wordsDetail.words}}</view>
			<view class="phoneticSymbol" v-if="wordsDetail.symbol">[{{wordsDetail.symbol}}]
			</view>
			<view class="explain">{{wordsDetail.pretations}}</view>
			<view class="title" v-if="wordsDetail.sentences">例句</view>
			<view class="exampleEn">{{wordsDetail.sentences}}</view>
			<!-- <view class="exampleZh">我是两天前来这儿的</view> -->
		</view>
		<view class="practiceFractionBox">
			<view class="practiceFraction" v-if="recordingStatus=='ended'&&wordsDetail.sourceObj">
				<view :class="autoColor(wordsDetail.sourceObj.total_score)">
					{{Math.round(wordsDetail.sourceObj.total_score)}}分
				</view>
				<img src="@/assets/phoneticPractice/分数-红@3x.png"
					v-if="wordsDetail.sourceObj.total_score<60&&recordingStatus=='ended'" />
				<img src="@/assets/phoneticPractice/分数-黄@3x.png"
					v-if="(wordsDetail.sourceObj.total_score>=60&&wordsDetail.sourceObj.total_score<=80)&&recordingStatus=='ended'" />
				<img src="@/assets/phoneticPractice/分数-绿@3x.png"
					v-if="wordsDetail.sourceObj.total_score>80&&recordingStatus=='ended'" />
				<view class="context">
					<view class="label">完成度</view>
					<view :class="autoColor(wordsDetail.sourceObj.integrity_score)">
						{{Math.round(wordsDetail.sourceObj.integrity_score) }}
					</view>
				</view>
				<view class="context">
					<view class="label">流利度</view>
					<view :class="autoColor(wordsDetail.sourceObj.fluency_score)">
						{{Math.round(wordsDetail.sourceObj.fluency_score) }}
					</view>
				</view>
				<view class="context">
					<view class="label">准确度</view>
					<view :class="autoColor(wordsDetail.sourceObj.accuracy_score)">
						{{Math.round(wordsDetail.sourceObj.accuracy_score)}}
					</view>
				</view>
			</view>
		</view>
		<view class="practiceButton" v-if="recordingStatus!='ended'">
			<!-- v-if="wordsDetail.wordFile" -->
			<view class="wordsVoice" >
		<!-- 			<img src="@/assets/phoneticPractice/声音@3x.png" v-if="!isPlayWords" @click="onlyPlayAudio" />
				<img src="@/assets/phoneticPractice/话筒效果-2.gif" v-else /> -->
			</view>
			<!-- 弹性盒占位 -->
			<!-- <view class="wordsVoice" v-else></view> -->
			<view class="wordsPlay">
				<!-- @click="tapeClick" -->
				<view class="circle-container" v-if="recordingStatus=='recording'">
					<svg class="circle-progress" viewBox="0 0 36 36" xmlns="http://www.w3.org/2000/svg">
						<circle class="circle-bg" cx="18" cy="18" r="16" fill="none" stroke="#ffffff"
							stroke-width="1" />
						<circle class="circle" cx="18" cy="18" r="16" fill="none" stroke="#0CB76C" stroke-width="1"
							stroke-dasharray="100.48" stroke-dashoffset="100.48" />
					</svg>
					<img src="@/assets/phoneticPractice/语音动画效果01.gif" style="position: absolute;" />
				</view>
				<img src="@/assets/phoneticPractice/录音@3x.png" v-if="wordsDetail.id&&recordingStatus=='notStarted'" />
			</view>
			<view class="myVoice"></view>
		</view>
		<!-- 填充盒子 -->
		<view class="fillBox"></view>
		<view class="practiceBottom" v-if="recordingStatus=='ended'">
			<view @click="againRead" class="again">重读</view>
			<view @click="handleHeaderLeft" class="next">完成</view>
		</view>
		<u-overlay :show="recordingStatus == 'evaluating'">
			<view class="loading">
				<u-loading-icon text="评分中..." color="#ffffff" textColor="#ffffff" textSize="18"></u-loading-icon>
			</view>
		</u-overlay>
		<!-- <u-loading-page :show="recordingStatus == 'evaluating'" loadingText="评分中..."
			bg-color="#e8e8e8"></u-loading-page> -->
		<!-- 	<audio ref="audioElement" :src="audioSrc" @ended="playEnded"></audio>
		<audio ref="dingAudioElement" :src="dingAudioSrc"></audio> -->
	</view>
</template>

<script setup>
	import {
		uploadFiles,
		savePhoneticPracticeScore,
		getPhoneticPracticeLogs
	} from '@/api/phoneticPractice'
	import IatRecorder from '@/utils/iatRecorder'
	let recordedChunks = [];
	let iatRecorder;
	let mediaRecorder;


	export default {
		data() {
			return {
				currentIndex: 0, //当前单词索引
				phoneticPracticeList: [], //练习单词列表
				wordsDetail: {}, //单词详情信息
				versionId: null,
				recordingStatus: 'notStarted', //录音状态 notStarted未开始  recording 录音中 ended 已结束 evaluating评测中
				isPlayWords: false, //是否正在播放单词
				audioElement: null,
				isOnlyPlayAudio: false, //只播放音频不触发录音
				videoTimeoutVal: null,
				sourceTimeoutVal: null,
				completeTimeoutVal: null,
				stream: null,
				dingAudioElement: null,
			}
		},
		onLoad(options) {
			if (options && options.versionId) {
				this.versionId = options.versionId
				this.currentIndex = options.index
				this.getLogsList()
			}
		},
		destroyed() {
			if (mediaRecorder) {
				this.stopRecording() //结束录音
			}
			if (this.stream) {
				this.stream.getTracks().forEach(track => track.stop())
			}
			if (iatRecorder) {
				iatRecorder.stop()
			}
			this.audioElement.destroy()
			this.audioElement = null
			clearTimeout(this.sourceTimeoutVal)
			clearTimeout(this.videoTimeoutVal)
			clearTimeout(this.completeTimeoutVal)
		},
		methods: {
			handleHeaderLeft() {
				uni.navigateBack({
					delta: 1
				})
			},
			autoColor(num) {
				if (num < 60) {
					return 'autoRed' //#FA192C
				} else if (num >= 60 && num <= 80) {
					return 'autoYellow' //#FF9917
				} else if (num > 80) {
					return 'autoGreed' //#0CB76C
				}
			},
			saveWords() {
				let obj = this.wordsDetail
				savePhoneticPracticeScore({
					versionId: this.versionId,
					wId: obj.wId,
					score: Math.round(obj.sourceObj.total_score),
					integrity: Math.round(obj.sourceObj.integrity_score),
					fluency: Math.round(obj.sourceObj.fluency_score),
					accuracy: Math.round(obj.sourceObj.accuracy_score),
					video: obj.video
				}).then(res => {

				})
			},
			stopRecording() {
				this.wordsDetail.recordedChunks = recordedChunks
				mediaRecorder.stop();
			},
			async startRecording() {
				recordedChunks = []
				this.stream = await navigator.mediaDevices.getUserMedia({
					audio: true
				});
				mediaRecorder = new MediaRecorder(this.stream);
				mediaRecorder.addEventListener('dataavailable', event => {
					recordedChunks.push(event.data);
				});
				mediaRecorder.start();
			},
			//语音识别
			tapeClick() {
				this.dingAudioElement = uni.createInnerAudioContext();
				this.dingAudioElement.src = "https://oss.bigchun.com/file/ding.mp3"
				this.dingAudioElement.autoplay = true;
				this.startRecording() //开始录音
				this.recordingStatus = 'recording'
				iatRecorder.start()
				this.videoTimeoutVal = setTimeout(() => {
					this.recordingStatus = 'evaluating'
					this.completeClick()
				}, 5000);
			},
			uploadFilePromise() {
				const blob = new Blob(recordedChunks, {
					type: "audio/webm;codecs=opus"
				});
				var file = new File([blob], this.wordsDetail.words + '-' + Date.now() + '.MP3', {
					type: 'audio/x-mpeg',
					lastModified: Date.now()
				});
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: 'https://d-xueer.bigchun.com/api/common/upload', // 仅为示例，非真实的接口地址
						file: file,
						header: {
							token: uni.getStorageSync('token'),
						},
						success: (res) => {
							let response = JSON.parse(res.data)
							if (response.code == 1) {
								setTimeout(() => {
									resolve(response)
								}, 1000)
							}
						}
					});
				})
			},
			//保存单词练习信息
			saveFollow() {
				let obj = this.wordsDetail
				savePhoneticPracticeScore({
					versionId: this.versionId,
					wId: obj.wId,
					score: Math.round(obj.sourceObj.total_score),
					integrity: Math.round(obj.sourceObj.integrity_score),
					fluency: Math.round(obj.sourceObj.fluency_score),
					accuracy: Math.round(obj.sourceObj.accuracy_score),
					video: obj.video
				}).then(res => {

				})
			},
			completeClick() {
				let that = this
				this.recordingStatus = 'evaluating'
				iatRecorder.stop()
				this.stopRecording() //结束录音
				this.completeTimeoutVal = setTimeout(async () => {
					if (iatRecorder.getScoreObj()) {
						that.wordsDetail.sourceObj = iatRecorder.getScoreObj()
						if (that.wordsDetail.sourceObj.total_score == 0) {
							that.sourceTimeoutVal = setTimeout(() => {
								that.againRead()
							}, 1000)
							return uni.showToast({
								title: '请提高朗读音量,以免影响评分',
								icon: 'none'
							})
						}
						let urlData = await that.uploadFilePromise()
						if (urlData.code == 1) {
							that.wordsDetail.video = urlData.data.url
							that.wordsDetail.fullVideo = urlData.data.fullurl
							that.recordingStatus = 'ended'
							that.saveFollow()
						}
					} else {
						uni.showToast({
							title: '录音解析失败',
							icon: 'none'
						})
						that.wordsDetail.sourceObj = null
					}
				}, 2000);
			},
			//播放结束
			playEnded() {
				if (this.isOnlyPlayAudio) {
					return false
				}
				this.isPlayWords = false
				this.tapeClick()
			},
			// 只播放音频不触发录音
			onlyPlayAudio() {
				if (this.recordingStatus != 'ended') {
					return
				}
				this.isOnlyPlayAudio = true
				this.audioElement = uni.createInnerAudioContext();
				this.audioElement.src = this.wordsDetail.wordFile
				this.audioElement.autoplay = true;
			},
			// 重读
			againRead() {
				this.wordsDetail.sourceObj = null
				this.recordingStatus = 'notStarted'
				this.playAudio()
			},
			// 播放音频
			playAudio() {
				let that = this
				this.isOnlyPlayAudio = false
				this.recordingStatus = 'playing'
				// 创建并播放音频对象
				this.audioElement = uni.createInnerAudioContext();
				this.audioElement.src = this.wordsDetail.wordFile
				this.audioElement.autoplay = true;
				this.audioElement.onEnded(() => {
					this.playEnded()
				});
			},
			//获取作业日志列表
			getLogsList() {
				getPhoneticPracticeLogs({
					versionId: this.versionId
				}).then(res => {
					if (res.code == 1) {
						this.phoneticPracticeList = res.data
						//获取单词详情信息
						this.getWordsDetail()
					}
				})
			},
			getWordsDetail() {
				for (var i = 0; i < this.phoneticPracticeList.length; i++) {
					if (this.currentIndex == i) {
						this.wordsDetail = this.phoneticPracticeList[this.currentIndex]
						iatRecorder = new IatRecorder({
							text: this.wordsDetail.words
						})
						this.playAudio()
					}
				}
			},
		}
	}
</script>

<style>
	page {
		min-height: 100%;
		background-color: #ffffff;
	}
</style>
<style lang="scss" scoped>
	.loading {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ffffff;
		height: 100%;
		font-size: 18px;

		.text {
			margin-left: 10px;
		}
	}

	.circle-container {
		width: 70px;
		/* 容器大小，根据需要调整 */
		height: 70px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.circle-progress {
		width: 100%;
		height: 100%;
	}

	.circle-bg {
		stroke: #FFFFFF;
		/* 背景圆线条颜色 */
	}

	.circle {
		/* 动画定义 */
		animation: progress 5s ease-out forwards;
	}

	@keyframes progress {
		0% {
			stroke-dashoffset: 100.48;
			/* 初始时，线条完全不可见 */
		}

		100% {
			stroke-dashoffset: 0;
			/* 结束时，线条完全可见 */
		}
	}

	.fillBox {
		height: 40px;
	}

	.practiceBottom {
		position: fixed;
		width: 100%;
		bottom: 0;
		height: 28px;
		background: #E7F8F0;
		color: #0CB76C;
		font-size: 12px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20px;
		box-sizing: border-box;

		.again,
		.next {
			width: 80px;
			height: 22px;
			line-height: 22px;
			text-align: center;
			border-radius: 18px;
			border: 1px solid #0CB76C;
		}
	}

	.practiceFractionBox {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 0 20px;

		.practiceFraction {
			display: inline-block;
			font-size: 28px;

			img {
				width: 55px;
				height: 12px;
				margin-bottom: 6px;
			}

			.context {
				margin-top: 5px;
				display: flex;
				align-items: center;
				color: #8E8E8E;
				font-size: 12px;

				.lebel {
					margin-right: 6px;
				}
			}
		}
	}


	.practiceButton {
		margin-top: 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 20px 20px;
		position: fixed;
		width: 100%;
		height: 110px;
		bottom: 28px;
		box-sizing: border-box;
		background-color: #FFFFFF;

		.wordsVoice {
			flex: 1;
			text-align: center;

			img {
				width: 26px;
				height: 20px;
			}
		}

		.wordsPlay {
			flex: 1;
			text-align: center;
			display: flex;
			justify-content: center;

			img {
				width: 52px;
				height: 52px;
			}
		}

		.myVoice {
			flex: 1;
			text-align: center;

			img {
				width: 26px;
				height: 26px;
			}
		}

		.complete {
			font-size: 16px;
			color: #0CB76C;
		}
	}

	.wordsDetailBox {
		width: 100%;
		height: 100%;
		background-color: #FFFFFF;
		overflow: scroll;

		.wordBox {
			padding: 54px 10px 15px;
			display: flex;
			flex-direction: column;

			.progressBox {
				display: flex;
				align-items: center;
				font-size: 16px;
				color: #8E8E8E;

				.active {
					color: #0CB76C;
				}

				.progress {
					flex: 1;
					margin-left: 13px;
					height: 2px;
					background: #E5E5E5;
					border-radius: 1px;
					position: relative;
				}

				.current {
					position: absolute;
					top: 0;
					left: 0;
					height: 2px;
					background: #0CB76C;
					border-radius: 1px;
				}
			}

			.words {
				text-align: center;
				font-size: 32px;
				font-weight: bold;
				color: #333333;
				margin-top: 20px;
			}

			.phoneticSymbol {
				margin-top: 10px;
				text-align: center;
				font-size: 18px;
				color: #8E8E8E;
			}

			.explain {
				margin-top: 10px;
				text-align: center;
				font-size: 14px;
				color: #8E8E8E;
			}

			.title {
				margin-top: 20px;
				text-align: center;
				font-size: 14px;
				color: #8E8E8E;
			}

			.image {
				width: 320px;
				height: 180px;
				margin: 30px auto 0px;
				background: #D8D8D8;
				border-radius: 10px;

				img {
					width: 100%;
					height: 100%;
				}
			}

			.exampleEn,
			.exampleZh {
				text-align: center;
				font-size: 14px;
				color: #8E8E8E;
				margin-top: 10px;
			}
		}
	}

	.autoRed {
		color: #FA192C !important;
	}

	.autoYellow {
		color: #FF9917 !important;
	}

	.autoGreed {
		color: #0CB76C !important;
	}
</style>